import React from 'react'
import { Button, Form, Input, } from 'antd'
import { connect } from 'react-redux'
import { registerAsync } from '../../../_redux/actions_async'
import { Link, Redirect } from 'react-router-dom'
import { setRegisterSuccess } from '../../../_redux/actions'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
}
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
}

export default class RegisterForm extends React.Component {
  onFinish = e => {
    console.log(e)
    this.props.registerAsync(e)
  }

  render () {
    if (this.props.registerSuccess) {
      this.props.setRegisterSuccess(false)
      return <Redirect to="/reg-success"/>
    }

    return (
      <Form
        {...formItemLayout}
        name="register"
        onFinish={this.onFinish}
        scrollToFirstError
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: '请输入用户名！' }]}
        >
          <Input/>
        </Form.Item>
        <Form.Item
          label="邮箱"
          name="email"
          rules={[{ required: true, message: '请输入邮箱！' }]}
        >
          <Input/>
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码！' }]}
        >
          <Input.Password/>
        </Form.Item>
        <Form.Item
          label="确认密码"
          dependencies={['password']}
          hasFeedback
          name="confirm"
          rules={[
            { required: true, message: '请确认密码！' },
            ({ getFieldValue }) => ({
              validator (rule, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve()
                }
                return Promise.reject('密码不一致！')
              }
            })
          ]}
        >
          <Input.Password/>
        </Form.Item>
        <Form.Item {...tailFormItemLayout}>
          <Button htmlType="submit" type="primary">注册</Button>
          <Link style={{ marginLeft: 20 }} to="/login">登陆</Link>
        </Form.Item>
      </Form>
    )
  }
}

RegisterForm = connect(
  ({ $GlobalState: { registerSuccess } }) => ({ registerSuccess }),
  { registerAsync, setRegisterSuccess }
)
(RegisterForm)